//
//  LS_CustomTabBarButton.m
//  breadPro
//
//  Created by 刘文超 on 2019/7/3.
//  Copyright © 2019 刘文超. All rights reserved.
//

#import "LS_CustomTabBarButton.h"
#import "LS_CustomTabBarController.h"
CGFloat LS_CustomButtonWidth = 0.0f;
UIButton<LS_CustomTabBarButtonDelegate> *LS_CustomButton = nil;
UIViewController *LS_CustomChildViewController = nil;


@implementation LS_CustomTabBarButton

+(void)registerSubclass
{
    if (![self conformsToProtocol:@protocol(LS_CustomTabBarButtonDelegate)]) {
        return;
    }
    
    Class<LS_CustomTabBarButtonDelegate> class = self;
    UIButton<LS_CustomTabBarButtonDelegate> *customButton = [class customButton];
    LS_CustomButton  = customButton;
    LS_CustomButtonWidth = customButton.frame.size.width;
    if ([[self class] respondsToSelector:@selector(customChildViewController)]) {
        LS_CustomChildViewController = [class customChildViewController];
        [[self class] addSelectViewControllerTarget:customButton];
        if ([[self class] respondsToSelector:@selector(indexOfCustomButtonInTabBar)]) {
           LS_CustomButtonIndex = [[self class] indexOfCustomButtonInTabBar];
        }else{
        [NSException raise:@"LS_CustomTabBarController" format:@"如果想使用customChildViewController样式，必须同时在自定义的customButton中实现 `+indexOfCustomButtonInTabBar`，来指定customButton的位置"];
        }
    }
}
+ (void)addSelectViewControllerTarget:(UIButton<LS_CustomTabBarButtonDelegate> *)customButton {
    id target = self;
    NSArray<NSString *> *selectorNamesArray = [customButton actionsForTarget:target forControlEvent:UIControlEventTouchUpInside];
    if (selectorNamesArray.count == 0) {
        target = customButton;
        selectorNamesArray = [customButton actionsForTarget:target forControlEvent:UIControlEventTouchUpInside];
    }
    [selectorNamesArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SEL selector =  NSSelectorFromString(obj);
        [customButton removeTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    }];
    [customButton addTarget:customButton action:@selector(customChildViewControllerButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)customChildViewControllerButtonClicked:(UIButton<LS_CustomTabBarButtonDelegate> *)sender
{
    sender.selected = YES;
    [self LS_tabBarController].selectedIndex = LS_CustomButtonIndex;
}
@end
